<%@ page language="java"
	import="java.util.*,
    java.util.Locale,
    org.json.*,
    org.pentaho.core.ui.SimpleUrlFactory,
    org.pentaho.core.system.PentahoSystem,
    org.pentaho.core.solution.HttpRequestParameterProvider,
    org.pentaho.core.solution.HttpSessionParameterProvider,
    org.pentaho.core.session.IPentahoSession,
    org.pentaho.messages.Messages,
    org.pentaho.core.util.UIUtil,
    org.pentaho.core.util.IUITemplater,
	org.pentaho.util.VersionHelper,
	org.pentaho.messages.util.LocaleHelper,
    org.pentaho.core.solution.ActionResource,
    org.pentaho.core.solution.IActionResource,
    org.pentaho.ui.component.INavigationComponent,
    org.pentaho.ui.component.NavigationComponentFactory,
    org.pentaho.core.repository.ISolutionRepository,
    org.pentaho.ui.ChartHelper,
    javax.servlet.*,
    javax.servlet.http.*,
    javax.servlet.jsp.*,
    java.net.HttpURLConnection,
    java.net.ProtocolException,
    java.net.URL,
    java.net.URLConnection,
    javax.servlet.jsp.tagext.*,
    org.pentaho.core.solution.SimpleParameterProvider,
    org.mapfish.geo.*,
    org.pentaho.commons.connection.*,
    org.pentaho.core.runtime.IRuntimeContext,
	java.io.*"%>
<%

/*
 * This software is provided under the terms
 * of GNU Lesser GPL License. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.gnu.org/copyleft/lesser.html. 
 * This code uses the Pentaho BI Platform API. 
 
 * @author Fabio D'Ovidio
 * @author Matteo Villari
*/

	response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
	HttpSession httpSession = request.getSession();
	String baseUrl = PentahoSystem.getApplicationContext().getBaseUrl();
	IPentahoSession userSession = UIUtil.getPentahoSession( request );
	HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider( request );
	HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider( userSession );
	// Load the customer data. Do this by running an action sequence defined in pentaho-solutions/samples/google/map1.xaction
	SimpleParameterProvider parameters = new SimpleParameterProvider();
    String xactionpath = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "action", null);
    String[] xaction = xactionpath.split(";");
    String path = xaction[0];
    String xact = xaction[1];
	ArrayList messages = new ArrayList();
	// 'results' will store the customer data
	IPentahoResultSet results = null;
    IPentahoMetaData metaData = null;
    IRuntimeContext runtime = null;
    try {
	// Run the action sequence
	runtime = ChartHelper.doAction( "dashboards",  path,  xact,  
			"MapOl.jsp",  parameters,  userSession,  messages,  null );
	// See if we have a valid result
    if( runtime != null ) {
		if( runtime.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS ) {
			if( runtime.getOutputNames().contains("data") ) {
				results = runtime.getOutputParameter( "data" ).getValueAsResultSet();
          			metaData = results.getMetaData();
			}
		}
       }
      } finally {
          if (runtime != null) {
          		// Now clean up 
              	runtime.dispose();
          }
      }

      
      String idFeature = new String();
      int n = results.getRowCount();
      int nc = metaData.getColumnCount();
      int posizione;
      String xactionparam = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "paramx", null);
      String geoserverUrl = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "url", null);
      String pos = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "pos", null);
      try{
      posizione = Integer.parseInt(pos);
      }
      catch (NumberFormatException nfe) {
             nfe.printStackTrace();
             posizione = 1000000;
      }
      
      String[] xactionparams  = xactionparam.split(";");
      
      int nparam = xactionparams.length;
      String[] paramname = new String[nparam];
      
      String layer = request.getParameter("layer");
      String ids = request.getParameter("id");
      String id = ids;

      Object[][] colHeaders = metaData.getColumnHeaders();
      //Instantiate GeoJsonFactory
      MfGeoFactory geoFactory = new MfGeoFactory() {
          public MfFeature createFeature(final String id, final MfGeometry geometry, final JSONObject properties) {
              return new MfFeature() {
                  public String getFeatureId() {
                      return id;
                  }
                  public MfGeometry getMfGeometry() {
                      return geometry;
                  }
                  public void toJSON(JSONWriter builder) throws JSONException {
                      Iterator iter = properties.keys();
                      while (iter.hasNext()){
                    	  String key = (String) iter.next();
                    	  Object value = properties.get(key);
                    	  builder.key(key).value(value);                    	  
                      }
                  }
          };
      }
      };
      //Create Output Collection of Features
      Collection outputFeatureCollection = new ArrayList();
      //Reads GeoJSON from GeoServer
      MfGeoJSONReader jsonReader = new MfGeoJSONReader(geoFactory);      
	for( int i=0; i<n; i++ ) {	
        //Feature id from resultSet  
		idFeature = results.getValueAt( i, posizione ).toString(); // ID 
        //Prepare wfsUrl to get feature from GeoServer filtering by "idFeature"  
        
        String wfsUrl = geoserverUrl+ "/geoserver/wfs?request=GetFeature&typename=topp:" + layer + "&Filter=<Filter><PropertyIsEqualTo><PropertyName>"+ id +"</PropertyName><Literal>"+ idFeature +"</Literal></PropertyIsEqualTo></Filter>&outputformat=json&version=1.0.0";
		//GeoJson from GeoServer
		String result = null;
        // Send a GET request to the servlet
        
    try
    {
    	URL url = new URL(wfsUrl);
        URLConnection conn = url.openConnection ();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null)
        {
        sb.append(line);        
        }
        rd.close();
        result = sb.toString();
               
        
        //featureCollection from GeoServer
        MfFeatureCollection featureCollection = (MfFeatureCollection) jsonReader.decode(result);
        List featureList = new ArrayList(featureCollection.getCollection());
        MfFeature feature = (MfFeature) featureList.get(0);
        
        //Geometry from GeoServer
        MfGeometry geom = feature.getMfGeometry();
        
        
		JSONObject jsonProperties = new JSONObject();
		
        for(int j=0; j<nc; j++){
        	jsonProperties.accumulate(colHeaders[0][j].toString(),results.getValueAt(i,j));
        	
        }
        MfFeature featureToCollect = geoFactory.createFeature(idFeature,geom,jsonProperties);
        outputFeatureCollection.add(featureToCollect);
      } catch (Exception e)
      {
      e.printStackTrace();
      }
	}
	
    JSONStringer stringer = new JSONStringer();
    MfGeoJSONWriter builder = new MfGeoJSONWriter(stringer);
    builder.encodeFeatureCollection(new MfFeatureCollection(outputFeatureCollection));
    out.println(stringer);

%>
